package com.kaifamiao.tags;

import java.io.IOException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class FormatTag extends SimpleTagSupport {

    private Object item;
    private String pattern;

    public FormatTag() {
    }

    public void doTag() throws JspException, IOException {

        String result = "";

        if ( item instanceof Date date ) {
            DateFormat df = new SimpleDateFormat(this.pattern);
            result = df.format(date);
        }

        if ( item instanceof Integer number ) {
            NumberFormat nf = new DecimalFormat(this.pattern);
            result = nf.format(number);
        }

        JspWriter out = this.getJspContext().getOut();
        out.println("<p style='text-align:center;border:1px solid blue;'>");
        out.println(result);
        out.println("</p>");
    }

    public Object getItem() {
        return this.item;
    }

    public void setItem(Object item) {
        this.item = item;
    }

    public String getPattern() {
        return this.pattern;
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }
}

